<script setup>
	import { computed, nextTick, ref } from 'vue'
	import { message } from 'ant-design-vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import MysqlDataset from './mysqlDataset.vue'
	import ApiDataset from './apiDataset/ApiDataset.vue'
	import { useSimpleQueryStore } from '@/views/plugin/dashboard/store/simpleQuery'
	import { useCustomQueryStore } from '@/views/plugin/dashboard/store/customQuery'
	import { useApiDatasetStore } from '@/views/plugin/dashboard/store/apiDataset'

	const simpleQueryStore = useSimpleQueryStore()
	const customQueryStore = useCustomQueryStore()
	const apiDatasetStore = useApiDatasetStore()

	const visible = ref(false)
	const mysqlDatasetRef = ref()
	const apiDatasetRef = ref()
	const connectorInfo = ref(null)

	const formData = ref({
		id: '',
		config: {},
		type: 'query' // 默认为简单查询类型
	})

	// 计算当前数据集组件类型
	const currentDatasetType = computed(() => {
		if (!connectorInfo.value) return 'mysql'

		const connectorType = connectorInfo.value.type
		if (['LOCAL_API', 'HTTP', 'EXTERNAL_API'].includes(connectorType)) {
			return 'api'
		}
		return 'mysql'
	})

	// 判断是否为API类型指标
	const isApiIndicator = computed(() => {
		return formData.value.type === 'api_query'
	})

	// 打开抽屉
	const onOpen = async (record) => {
		visible.value = true
		if (record) {
			formData.value = {
				...{
					id: '',
					dataConnectorId: '',
					type: 'query',
					itemConfig: {
						// 驼峰转换状态
						enableCamelCase: false,
						// 选中的列
						selectedColumns: [],
						// 格式化配置
						formatConfig: [],
						// 表格列定义
						columns: [],
						// 表名
						tableName: '',
						// 查询条件
						conditions: [],
						// 排序
						sorts: [],
						// API相关配置
						apiPath: '',
						apiMethod: 'GET',
						apiParams: {}
					}
				},
				...record
			}

			// 获取连接器信息以确定数据集类型
			if (formData.value.dataConnectorId) {
				try {
					const connectorList = await dataConnectorApi.list({ id: formData.value.dataConnectorId })
					if (connectorList && connectorList.length > 0) {
						connectorInfo.value = connectorList[0]
					}
				} catch (error) {
					console.error('获取连接器信息失败:', error)
				}
			}
		}

		nextTick(() => {
			// 根据指标类型或连接器类型决定使用哪个组件
			if (isApiIndicator.value || currentDatasetType.value === 'api') {
				apiDatasetRef.value?.onOpen(formData.value)
			} else {
				mysqlDatasetRef.value?.onOpen(formData.value)
			}
		})
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
		formData.value = {
			id: '',
			config: {},
			type: 'query'
		}
		connectorInfo.value = null

		// 清空自定义查询store中的数据
		customQueryStore.$reset()
		customQueryStore.setFormData({
			id: '',
			dataConnectorId: '',
			datasetId: '',
			config: {
				sql: 'SELECT * FROM ',
				params: [],
				selectedTables: [],
				tableFields: {}
			}
		})
		customQueryStore.updateQueryResult([])

		// 清空简单查询store中的数据
		simpleQueryStore.$reset()
		simpleQueryStore.setFormData({
			id: '',
			dataConnectorId: '',
			itemConfig: {
				enableCamelCase: false,
				selectedColumns: [],
				formatConfig: [],
				columns: [],
				tableName: '',
				conditions: [],
				sorts: []
			}
		})

		// 清空API数据集store中的数据
		apiDatasetStore.$reset()
		apiDatasetStore.setFormData({
			id: '',
			dataConnectorId: '',
			datasetId: '',
			itemConfig: {
				apiPath: '',
				apiMethod: 'GET',
				apiParams: {},
				selectedColumns: [],
				formatConfig: []
			}
		})
		apiDatasetStore.updateQueryResult([])
	}

	// 保存数据集配置
	const onSave = async () => {
		try {
			// 根据当前数据集类型获取对应的store数据
			let config, itemConfig

			if (isApiIndicator.value || currentDatasetType.value === 'api') {
				// API数据集配置
				const currentType = apiDatasetRef.value?.currentType || formData.value.type || 'query'

				if (currentType === 'query' || currentType === 'api_query') {
					config = apiDatasetStore.formData
					if (!config) {
						message.error('请完善API数据集配置')
						return
					}
					itemConfig = config.itemConfig
				} else {
					// API自定义查询暂不支持
					message.error('API连接器暂不支持自定义查询')
					return
				}
			} else {
				// MySQL数据集配置
				const currentType = mysqlDatasetRef.value?.currentType || formData.value.type || 'query'

				if (currentType === 'query') {
					config = simpleQueryStore.formData
					if (!config) {
						message.error('请完善数据集配置')
						return
					}
					itemConfig = config.itemConfig
				} else {
					config = customQueryStore.formData
					if (!config) {
						message.error('请完善数据集配置')
						return
					}
					// 自定义查询的配置结构与简单查询不同，需要适配
					itemConfig = config.config
				}
			}

			const params = {
				id: formData.value.id,
				datasetId: config.datasetId,
				itemConfig: itemConfig,
				customItemConfig:
					currentDatasetType.value === 'mysql' && mysqlDatasetRef.value?.currentType !== 'query'
						? config.config
						: undefined
			}
			await datasetApi.saveItemConfig(params)
			message.success('保存成功')
			emit('loadData')
			onClose()
		} catch (error) {
			message.error('保存失败：' + error.message)
		}
	}

	defineExpose({
		onOpen
	})

	const emit = defineEmits(['loadData'])
</script>

<template>
	<a-drawer
		title="数据指标配置"
		placement="right"
		:width="'90%'"
		:open="visible"
		@close="onClose"
		:destroy-on-close="true"
	>
		<!-- 根据指标类型或连接器类型显示不同的数据集配置组件 -->
		<api-dataset
			v-if="isApiIndicator || currentDatasetType === 'api'"
			ref="apiDatasetRef"
			@loadData="emit('loadData')"
		/>
		<mysql-dataset v-else ref="mysqlDatasetRef" @loadData="emit('loadData')" />

		<template #footer>
			<div style="text-align: right">
				<a-button style="margin-right: 8px" @click="onClose">取消</a-button>
				<a-button type="primary" @click="onSave">保存</a-button>
			</div>
		</template>
	</a-drawer>
</template>
<style scoped>
	:deep(.ant-drawer-body) {
		padding: 12px;
	}
</style>
